//
//  AccountDynamicView.m
//  NOAHWM
//
//  Created by Ryan on 13-6-24.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "AccountDynamicView.h"
#import "NYAccountDynamic.h"
#import "ListDynamicCell.h"
#import "TimeDynamicCell.h"
#import "DynamicTodayCell.h"
#import "NSDate+RYAdditions.h"
#import "JSON.h"

#define kDynamicListTypeFileName @"AccountDynamicType"

@interface AccountDynamicView()

@property (nonatomic, retain) NSMutableDictionary *leftDict;
@property (nonatomic, retain) NSMutableArray *rightArray;
@property (nonatomic, retain) NSMutableArray *futureArray;
@property (nonatomic, retain) NSDictionary *dynamicTypeDict;
@property (nonatomic, assign) CGFloat lastOffsetY;

@end

@implementation AccountDynamicView

@synthesize highlightedImageView,leftButton,rightButton;
@synthesize leftContainView,rightContainView;
@synthesize tabImageView,tab1Button,tab2Button,tab3Button,tab4Button;
@synthesize leftTableView,rightTableView;
@synthesize accountDynamics;
@synthesize listSubType,listType;
@synthesize leftDict,dynamicTypeDict,rightArray,futureArray;
@synthesize arrowImageView,isFullScreen;
@synthesize lastOffsetY;

#pragma mark - UIView methods

- (void)awakeFromNib
{
    [super awakeFromNib];
    NSString *path = [[NSBundle mainBundle] pathForResource:kDynamicListTypeFileName ofType:@"plist"];
    self.dynamicTypeDict = [NSDictionary dictionaryWithContentsOfFile:path];
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [arrowImageView release];
    [futureArray release];
    [rightArray release];
    [dynamicTypeDict release];
    [leftDict release];
    [rightTableView release];
    [accountDynamics release];
    [leftTableView release];
    [tabImageView release];
    [tab1Button release];
    [tab2Button release];
    [tab3Button release];
    [tab4Button release];
    [highlightedImageView release];
    [leftButton release];
    [rightButton release];
    [super dealloc];
}

#pragma mark - Public methods

- (IBAction)listButtonClicked:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if(btn == self.leftButton)
    {
        self.listType = kDynamicList;
        [self tabButtonClicked:self.tab1Button];
        self.highlightedImageView.image = [UIImage imageNamed:@"bg_dynamic_list@2x.png"];
        self.leftContainView.hidden = NO;
        self.rightContainView.hidden = YES;
        self.arrowImageView.hidden = YES;
    }
    else
    {
        self.listType = kDynamicTime;
        self.highlightedImageView.image = [UIImage imageNamed:@"bg_dynamic_time@2x.png"];
        self.leftContainView.hidden = YES;
        self.rightContainView.hidden = NO;
        [self.rightTableView setContentOffset:CGPointZero];
        self.arrowImageView.hidden = NO;
        [self loadTimeDynamicList];
    }
    [UIView animateWithDuration:0.2f animations:^(void){
        self.highlightedImageView.frame = btn.frame;
    }];
}

- (void)loadTimeDynamicList
{
    //添加[NSNull null]值来显示今天的cell
    self.rightArray = [NSMutableArray array];
    self.futureArray = [NSMutableArray array];
    if(self.accountDynamics.count == 0)
    {
        //无数据的时候，只显示今天cell
        [self.rightArray addObject:[NSNull null]];
    }
    else
    {
        NSString *stringDate = [NSDate dateToStringByFormat:@"yyyy-MM-dd" date:[NSDate date]];
        NYAccountDynamic *maxAD = [self.accountDynamics objectAtIndex:0];
        NYAccountDynamic *minAD = [self.accountDynamics lastObject];
        if([stringDate compare:maxAD.line_time options:NSNumericSearch] == NSOrderedSame ||
           [stringDate compare:maxAD.line_time options:NSNumericSearch] == NSOrderedDescending)
        {
            //当今天日期大于等于最大值时，today+all
            [self.rightArray addObject:[NSNull null]];
            [self.rightArray addObjectsFromArray:self.accountDynamics];
        }
        else if([stringDate compare:minAD.line_time options:NSNumericSearch] == NSOrderedAscending)
        {
            //当今天日期小于最小值时，last+today
            [self.rightArray addObject:self.accountDynamics.lastObject];
            [self.rightArray addObject:[NSNull null]];
            for(NSInteger i = 0; i< self.accountDynamics.count - 2; i++)
            {
                [self.futureArray addObject:[self.accountDynamics objectAtIndex:i]];
            }
        }
        else
        {
            NSInteger i;
            for(i = 0; i < self.accountDynamics.count-2; i++)
            {
                NYAccountDynamic *curAD = [self.accountDynamics objectAtIndex:i];
                NYAccountDynamic *nextAD = [self.accountDynamics objectAtIndex:i+1];
                NSString *stringDate = [NSDate dateToStringByFormat:@"yyyy-MM-dd" date:[NSDate date]];
                if([stringDate compare:curAD.line_time options:NSNumericSearch] == NSOrderedAscending && ([stringDate compare:nextAD.line_time options:NSNumericSearch] == NSOrderedDescending || [stringDate compare:nextAD.line_time options:NSNumericSearch] == NSOrderedSame))
                {
                    break;
                }
            }
            [self.rightArray addObject:[self.accountDynamics objectAtIndex:i]];
            [self.rightArray addObject:[NSNull null]];
            for(NSInteger index = i+1; index < self.accountDynamics.count; index++)
            {
                [self.rightArray addObject:[self.accountDynamics objectAtIndex:index]];
            }
            for(NSInteger j = 0; j < i; j++)
            {
                [self.futureArray addObject:[self.accountDynamics objectAtIndex:j]];
            }
        }
    }
    [self.rightTableView reloadData];
    
    self.lastOffsetY = kTimeDynamicCellHeight*self.futureArray.count;
    [self.rightTableView setContentOffset:CGPointMake(0, kTimeDynamicCellHeight*self.futureArray.count)];
}

- (IBAction)tabButtonClicked:(id)sender
{
    [self.leftTableView setContentOffset:CGPointZero];
    UIButton *btn = (UIButton *)sender;
    self.listSubType = (ListSubType)(btn.tag);
    if(btn == self.tab1Button)
    {
        self.tabImageView.image = [UIImage imageNamed:@"tab1@2x.png"];
    }
    else if(btn == self.tab2Button)
    {
        self.tabImageView.image = [UIImage imageNamed:@"tab2@2x.png"];
    }
    else if(btn == self.tab3Button)
    {
        self.tabImageView.image = [UIImage imageNamed:@"tab3@2x.png"];
    }
    else
    {
        self.tabImageView.image = [UIImage imageNamed:@"tab4@2x.png"];
    }
    [UIView animateWithDuration:0.2f animations:^(void){
        self.tabImageView.frame = btn.frame;
    }];
    
    //根据类型过滤
    NSString *dynamicType = [self.dynamicTypeDict objectForKey:[NSString stringWithFormat:@"%d",btn.tag]];
    
    self.leftDict = [NSMutableDictionary dictionary];
    for(NYAccountDynamic *nyad in self.accountDynamics)
    {
        if(![nyad.is_view isEqualToString:@"1"])
            continue;
        if([nyad.objecttype isEqualToString:dynamicType])
        {
            NSString *key = nyad.dynamicMonth;
            NSMutableArray *array = nil;
            if([self.leftDict objectForKey:key] == nil)
            {
                array = [NSMutableArray array];
                [self.leftDict setObject:array forKey:key];
            }
            else
            {
                array = [self.leftDict objectForKey:key];
            }
            [array addObject:nyad];
        }
    }
    //给所有日期对应的数据降序排序
    for(NSString *key in self.leftDict.allKeys)
    {
        NSMutableArray *array = [self.leftDict objectForKey:key];
        [array sortUsingComparator:^NSComparisonResult(NYAccountDynamic *dyn1, NYAccountDynamic *dyn2){
            if([dyn1.dynamicDay compare:dyn2.dynamicDay options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([dyn1.dynamicDay compare:dyn2.dynamicDay options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
    }
    self.lastOffsetY = 0;
    [self.leftTableView reloadData];
}

- (void)callServerToGetDynamicList:(NSString *)accountId
                         productId:(NSString *)productId
{
    self.accountDynamics = [NSMutableArray array];
    NSString *suburl = [NSString stringWithFormat:kAccountDynamicListUrl,@"jsonp",accountId,productId,@""];
    suburl = [suburl stringByAppendingString:@"app000028"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView == self.leftTableView)
    {
        return [self.leftDict allKeys].count;
    }
    else
    {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == self.leftTableView)
    {
        NSArray *allkeys = [[self.leftDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
            if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
        NSString *key = [allkeys objectAtIndex:section];
        NSArray *array = [self.leftDict objectForKey:key];
        return array.count;
    }
    else
    {
        return self.futureArray.count+self.rightArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.leftTableView)
    {
        static NSString *dynamicCellIdentify = @"dynamicCellIdentify";
        ListDynamicCell *dynamicCell = [tableView dequeueReusableCellWithIdentifier:dynamicCellIdentify];
        if(nil == dynamicCell)
        {
            NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"ListDynamicCell" owner:self options:nil];
            dynamicCell = [nibs lastObject];
            
            UIImageView *selectionView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_selection@2x.png"]];
            dynamicCell.selectedBackgroundView = selectionView;
            [selectionView release];
        }
        
        NSArray *allkeys = [[self.leftDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
            if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
        NSString *key = [allkeys objectAtIndex:indexPath.section];
        NSArray *array = [self.leftDict objectForKey:key];
        NYAccountDynamic *nyad = [array objectAtIndex:indexPath.row];
        dynamicCell.nameLabel.text = nyad.fapp_title;
        dynamicCell.desLabel.text = nyad.article_info;
//        dynamicCell.desLabel.text = @"测试文字越界是的情况试文字越界是的试文字越界是的\nhellowrold测试文字越界是的情况试文字越界是的情况";
        dynamicCell.weekdayLabel.text = nyad.dynamicWeekday;
        dynamicCell.dayLabel.text = nyad.dynamicDay;
        return dynamicCell;
    }
    else
    {
        id obj = nil;
        
        if(indexPath.row < self.futureArray.count)
            obj = [self.futureArray objectAtIndex:indexPath.row];
        else
        {
            NSInteger index = indexPath.row - self.futureArray.count;
            obj = [self.rightArray objectAtIndex:index];
        }
        
        if([obj isKindOfClass:[NSNull class]])
        {
            static NSString *todayCellIdentify = @"todayCellIdentify";
            DynamicTodayCell *todayCell = [tableView dequeueReusableCellWithIdentifier:todayCellIdentify];
            if(nil == todayCell)
            {
                NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"DynamicTodayCell" owner:self options:nil];
                todayCell = [nibs lastObject];
                todayCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return todayCell;
        }
        else
        {
            NYAccountDynamic *nyad = (NYAccountDynamic *)obj;
            
            static NSString *timeCellIdentify = @"timeCellIdentify";
            TimeDynamicCell *timeCell = [tableView dequeueReusableCellWithIdentifier:timeCellIdentify];
            if(nil == timeCell)
            {
                NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"TimeDynamicCell" owner:self options:nil];
                timeCell = [nibs lastObject];
                timeCell.selectionStyle = UITableViewCellSelectionStyleNone;
//                UIImageView *bgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_selection@2x.png"]];
//                timeCell.selectedBackgroundView = bgView;
//                [bgView release];
            }
            timeCell.nameLabel.text = nyad.fapp_title;
            timeCell.desLabel.text = nyad.article_info;
            timeCell.typeIconImageView.image = [UIImage imageNamed:[self.dynamicTypeDict objectForKey:nyad.objecttype]];

            NSString *stringDate = [NSDate dateToStringByFormat:@"yyyy-MM-dd" date:[NSDate date]];
            if([stringDate isEqualToString:nyad.line_time])
            {
                timeCell.dateLabel.textColor = [UIColor colorWithRed:236.f/255 green:78.f/255 blue:27.f/255 alpha:1.f];
                timeCell.dateLabel.highlightedTextColor = [UIColor colorWithRed:236.f/255 green:78.f/255 blue:27.f/255 alpha:1.f];
            }
            else
            {
                timeCell.dateLabel.textColor = [UIColor colorWithRed:175.f/255 green:144.f/255 blue:96.f/255 alpha:1.f];
                timeCell.dateLabel.highlightedTextColor = [UIColor colorWithRed:175.f/255 green:144.f/255 blue:96.f/255 alpha:1.f];
            }
            timeCell.dateLabel.text = nyad.line_time;
            return timeCell;
        }
    }
}

#pragma mark - UIScrollViewDelegate methods
- (void)fullSelector
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowAccountListFullScreenNotification object:nil];
}

- (void)halfSelector
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowAccountListHalfScreenNotification object:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    CGFloat currentOffsetY = scrollView.contentOffset.y;
    if(currentOffsetY > self.lastOffsetY)
    {
        //向上滚动
        if(!self.isFullScreen)
        {
            self.isFullScreen = YES;
            //设置全屏
            [[NSNotificationCenter defaultCenter] postNotificationName:kShowAccountListFullScreenNotification object:nil];
        }
    }
    else
    {
        //向下滚动
        if(self.isFullScreen && currentOffsetY < 0)
        {
            self.isFullScreen = NO;
            //取消全屏
            [[NSNotificationCenter defaultCenter] postNotificationName:kShowAccountListHalfScreenNotification object:nil];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView == self.rightTableView)
    {
        if(scrollView.contentOffset.y <= 0)
            self.arrowImageView.hidden = YES;
        else
        {
            self.arrowImageView.hidden = NO;
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.lastOffsetY = scrollView.contentOffset.y;
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(tableView == self.leftTableView)
    {
        return 20.f;
    }
    else
        return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.leftTableView)
    {
        return kListDynamicCellHeight;
    }
    else
    {
        if(indexPath.row < self.futureArray.count)
            return kTimeDynamicCellHeight;
        
        NSInteger index = indexPath.row - self.futureArray.count;
        id obj = [self.rightArray objectAtIndex:index];
        if([obj isKindOfClass:[NSNull class]])
            return kDynamicTodayCellHeight;
        else
            return kTimeDynamicCellHeight;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(tableView == self.leftTableView)
    {
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.sectionHeaderHeight)];
        sectionView.backgroundColor = [UIColor clearColor];
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:sectionView.bounds];
        bgImageView.image = [UIImage imageNamed:@"bg_dynamicSection@2x.png"];
        [sectionView addSubview:bgImageView];
        [bgImageView release];
        
        NSArray *allkeys = [[self.leftDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
            if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
        NSString *key = [allkeys objectAtIndex:section];
        
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.f, 0, tableView.frame.size.width-30.f, tableView.sectionHeaderHeight)];
        dateLabel.backgroundColor = [UIColor clearColor];
        dateLabel.textColor = [UIColor colorWithRed:28.f/255 green:28.f/255 blue:28.f/255 alpha:1.f];
        dateLabel.font = [UIFont systemFontOfSize:14.f];
        /**
         设置日期
         */
        dateLabel.text = key;
        
        [sectionView addSubview:dateLabel];
        [dateLabel release];
        return [sectionView autorelease];
    }
    else
    {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.rightTableView)
        return;
    
    NYAccountDynamic *nyAD = nil;
    if(tableView == self.leftTableView)
    {
        NSArray *allkeys = [[self.leftDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
            if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
        NSString *key = [allkeys objectAtIndex:indexPath.section];
        NSArray *array = [self.leftDict objectForKey:key];
        nyAD = [array objectAtIndex:indexPath.row];
    }
    else
    {
        if(indexPath.row < self.futureArray.count)
            nyAD = [self.futureArray objectAtIndex:indexPath.row];
        else
        {
            NSInteger index = indexPath.row - self.futureArray.count;
            nyAD = [self.rightArray objectAtIndex:index];
        }
    }
    if(nil == nyAD.article_id || [nyAD.article_id isEqualToString:@""])
        return;
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowDynamicDetailViewNotification object:nyAD];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        NSArray *array = [dict objectForKey:@"list"];
        for(NSDictionary *dynamicDict in array)
        {
            NYAccountDynamic *nyad = [[NYAccountDynamic alloc] init];
            for(NSString *key in [dynamicDict allKeys])
            {
                id value = [dynamicDict objectForKey:key];
                @try {
                    [nyad setValue:value forKey:key];
                }
                @catch (NSException *exception) {
                    NSLog(@"试图添加不存在的key: %@到NYAccountDynamic实例中.",key);
                }
            }
            NSString *lineTime = nyad.line_time;
            NSDate *lineDate = [NSDate dateFromStringByFormat:@"yyyy-MM-dd" string:lineTime];
            NSString *weekday = [NSDate weekdataForDate:lineDate];
            nyad.dynamicWeekday = weekday;
            
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDateComponents *component = [calendar components:NSDayCalendarUnit fromDate:lineDate];
            nyad.dynamicDay = [NSString stringWithFormat:@"%d",component.day];
            nyad.dynamicMonth = [NSDate dateToStringByFormat:@"yyyy-MM" date:lineDate];
            [self.accountDynamics addObject:nyad];
            [nyad release];
        }
        [self listButtonClicked:self.leftButton];
    }
    else
    {
//        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

@end
